package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //员工用户名重复异常处理
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//捕获什么类型异常
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.info(e.getMessage());
        //将异常信息以空格分割
        if (e.getMessage().contains("Duplicate entry")) {
            String[] splits = e.getMessage().split(" ");
                String msg = splits[2] + "用户名已存在";
                return R.error(msg);
        }
        return R.error("未知错误");
    }

    //自定义异常处理
    @ExceptionHandler(CustomException.class)//捕获什么类型异常
    public R<String> exceptionHandler(CustomException e) {

        return R.error(e.getMessage());
    }
}
